﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Web.Routing;

namespace Vit.Web.Mvc.DataAnnotations
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class ReadOnlyOnAttribute : ValidationAttribute, IClientValidatable
    {
        public ReadOnlyOnAttribute(bool onCreate, bool onEdit)
            : this(onCreate, onEdit, "EntityID")
        {
        }

        public ReadOnlyOnAttribute(bool onCreate, bool onEdit, string additionalFields)
        {
            OnCreate = onCreate;
            OnEdit = onEdit;
            AdditionalFields = additionalFields;
        }

        public override bool IsValid(object value)
        {
            return true;
        }

        public bool OnCreate { get; set; }
        public bool OnEdit { get; set; }
        public string AdditionalFields { get; set; }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ModelClientValidationRule rule = new ModelClientValidationRule()
                {
                    ErrorMessage = ErrorMessage,
                    ValidationType = "readonlyon"
                };

            rule.ValidationParameters["oncreate"] = OnCreate;
            rule.ValidationParameters["onedit"] = OnEdit;
            rule.ValidationParameters["additionalfields"] = AdditionalFields;

            yield return rule;
        }
    }
}
